package vn.vfriends.mcms.admin.bean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.mcms.admin.model.Role;
import vn.vfriends.mcms.admin.model.Site;
import vn.vfriends.mcms.admin.model.User;
import vn.vfriends.mcms.admin.service.RoleService;
import vn.vfriends.mcms.admin.service.SiteService;
import vn.vfriends.mcms.admin.service.UserService;
import vn.vfriends.mcms.admin.service.impl.exceptions.ViolationException;

/**
 *
 * @author tuan@vfriends.vn
 */
@Named
@ConversationScoped
public class RegisterBean implements Serializable {

    private static final Logger logger = LoggerFactory.getLogger(RegisterBean.class);
    
    private String username;
    
    private String email;
    
    private String password;
    
    private String reTypePassword;
    
    @Inject private UserService userService;
    
    @Inject private RoleService roleService;
    
    @Inject private SiteService siteService;
    
    @Inject private Conversation conversation;
    
    @PostConstruct
    public void init() {
        if (conversation.isTransient()) {
            conversation.begin();
        }
    }

    public Conversation getConversation() {
        return conversation;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getReTypePassword() {
        return reTypePassword;
    }

    public void setReTypePassword(String reTypePassword) {
        this.reTypePassword = reTypePassword;
    }
    
    public void registerAction() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            if(!this.password.equals(this.reTypePassword)) {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Nhập lại mật khẩu không khớp", ""));
                return;
            } else {
                //  Check username
                User user = this.userService.findUserByUsername(username.toLowerCase());
                if(user != null) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Tên đăng nhập đã được sử dụng", ""));
                    return;
                }
                
                //  Check site's name
                Site site = this.siteService.findSiteByName(username);
                if(site != null) {
                    FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Tên đăng nhập đã được sử dụng", ""));
                    return;
                }
                
                user = new User();
                user.setUsername(this.username.toLowerCase());
                user.setEmail(this.email);
                user.setPassword(DigestUtils.md5Hex(this.password));
                user.setActivated(true);
                List<Role> roles = new ArrayList<Role>();
                Role customerRole = this.roleService.findRoleByCode(Role.RoleCode.CUSTOMER);
                roles.add(customerRole);
                user.setRoles(roles);
                
                userService.createUser(user);
                
                //  Create site
                site = new Site();
                site.setName(username);
                site.setActivated(true);
                site.setUser(user);
                
                this.siteService.createSite(site);
            }
            context.getExternalContext().redirect("success.jsf");
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            if(ex instanceof ViolationException) {
                List<String> messages = ((ViolationException)ex).getMessages();
                for(String mess : messages) {
                    if(!StringUtils.isEmpty(mess)) {
                        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, mess, ""));
                    }
                }
            } else {
                context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), ""));
            }
        }
    }
}
